package cn.hd01.web.controller;

import cn.hd01.repository.entity.Upload;
import cn.hd01.service.UploadService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/upload")
@Auth
public class UploadController {
    private static final List<Upload> empty = new ArrayList<>(0);

    @Autowired
    private UploadService uploadService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    public String view() {
        return "upload";
    }

    @ResponseBody
    @RequestMapping(path = "/", method = RequestMethod.POST)
    public int userView(@RequestParam("file") MultipartFile[] file) {
        System.out.println(file.length);
        for (MultipartFile f : file) {
            try {
                System.err.println(f.getOriginalFilename());
                f.transferTo(new File("sssssss_" + f.getOriginalFilename()));
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        return file.length;
    }

    @ResponseBody
    @RequestMapping(path = "/add/{type}/{refId}", method = RequestMethod.POST)
    public List<Upload> addUploadFile(@PathVariable("type") String type, @PathVariable("refId") Integer refId,
                             @RequestParam("file") MultipartFile[] files) {
        if (files.length == 0) {
            return empty;
        }

        return uploadService.saveUploadAndFile(files, type, refId);
    }

    @ResponseBody
    @RequestMapping(path = "/get/{type}/{refId}", method = RequestMethod.GET)
    public List<Upload> getUploadFile(@PathVariable("type") String type, @PathVariable("refId") Integer refId) {
        return uploadService.findByTypeAndRefIdOrderBySortAsc(type, refId);
    }

    @ResponseBody
    @RequestMapping(path = "/modify", method = RequestMethod.POST)
    public void modifyUpload(Upload upload){
        uploadService.save(upload);
    }

    @ResponseBody
    @RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
    public void delete(@PathVariable("id") Integer id){
        uploadService.delete(id);
    }
    
    @Auth(AuthType.OFF)
    @RequestMapping(path = "/img/{id}", method = RequestMethod.GET)
    public void img(@PathVariable Integer id, HttpServletResponse response){
        try {
        	response.setContentType("image/png");
			uploadService.download(id, response.getOutputStream());
		} catch (Exception e) {
		    //ignor
		}finally{
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				//ignor
			}
		}
    }

}
